﻿using Microsoft.Win32;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Events;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Media.Media3D;
using System.Windows.Threading;
using Wpf.Netdisk.Extensions; 
using Wpf.Netdisk.Models;
using Wpf.Netdisk.Models.Dto.Main;
using Wpf.Netdisk.Models.Entity;
using Wpf.Netdisk.Models.Event;
using Wpf.Netdisk.Services.Implement;
using Wpf.Netdisk.Services.Interface;

namespace Wpf.Netdisk.ViewModels
{
    public class MainViewModel: BindableBase
    {
        #region 属性
        
        //定时器
        private DispatcherTimer dispatcherTimer;
        private string height;

        public string Height
        {
            get { return height; }
            set { height = value; }
        }

        //网速
        private string networkSpeed;

        public string NetworkSpeed
        {
            get { return networkSpeed; }
            set { networkSpeed = value; RaisePropertyChanged(); }
        }
        private Visibility isTopVisibility;

        public Visibility IsTopVisibility
        {
            get { return isTopVisibility; }
            set { isTopVisibility = value;RaisePropertyChanged(); }
        }

        //文件夹id
        private string folderId;
        public string FolderId
        {
            get { return folderId; }
            set { folderId = value; RaisePropertyChanged(); }
        }
        //用户名称
        public string UserName { get; set; }
        private readonly IRegionManager _regionManager;
        private readonly IEventAggregator _eventAggregator;

        /// <summary>
        /// 导航属性
        /// </summary>
        public DelegateCommand<MenuBar> NavigateCommand { get; private set; }

        private IRegionNavigationJournal journal;
        private ObservableCollection<MenuBar> menuBars;
        public ObservableCollection<MenuBar> MenuBars
        {
            get { return menuBars; }
            set { menuBars = value; RaisePropertyChanged(); }
        }
        public DelegateCommand<OpenFileDialog> UploadCommand { get; set; }
        public DelegateCommand<string> ExecuteCommand { get; set; }
        private readonly INetdiskFolderService _netdiskFolderService;
        private bool isRightDrawerOpen;
        public bool IsRightDrawerOpen
        {
            get { return isRightDrawerOpen; }
            set { isRightDrawerOpen = value; RaisePropertyChanged(); }
        }
        private NetdiskFolderInfo currentInfo;

        public NetdiskFolderInfo CurrentInfo
        {
            get { return currentInfo; }
            set { currentInfo = value; RaisePropertyChanged(); }
        }
        #endregion

        #region 计算实时网速
        public void InitNetWorkSpeed()
        {
            dispatcherTimer = new DispatcherTimer();
            dispatcherTimer.Tick += new EventHandler(timer_Tick);
            dispatcherTimer.Interval = TimeSpan.FromMilliseconds(100);
            dispatcherTimer.Start(); 
        }
        public void timer_Tick(object sender, EventArgs e)
        {
            NetworkSpeed network = new();

            var down = Math.Round(Convert.ToDouble(network.DownloadSpeed) / 1024, 2);
            if (down > 0 && down < 1024)
            {
                NetworkSpeed = down.ToString("0.##") + "KB";
            }
            else if (down > 1024)
            {
                down = down / 1024;
                NetworkSpeed = down.ToString("0.##") + "MB";
            }
            else
            {
                NetworkSpeed = 15 + "KB";
            }
        }
        #endregion

        
        public MainViewModel(IRegionManager regionManager, IContainerProvider containerProvider, IEventAggregator eventAggregator)
        {
            _netdiskFolderService = containerProvider.Resolve<INetdiskFolderService>();
            UserName = "rookie";
            MenuBars = new ObservableCollection<MenuBar>();
            UploadCommand = new DelegateCommand<OpenFileDialog>(Upload);
            CreateMenuBar();
            ExecuteCommand = new DelegateCommand<string>(Execute);
            NavigateCommand = new DelegateCommand<MenuBar>(Navigate);
            _regionManager = regionManager;
            this._eventAggregator = eventAggregator;
            var @event = _eventAggregator.GetEvent<TellMainFolderIdEvent>();
            @event.Subscribe(TellMainFolderId);
            InitNetWorkSpeed();
        }
        private void TellMainFolderId(string foldId)
        {
            FolderId = foldId;
        }
        
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="obj"></param>
        private async void Upload(OpenFileDialog obj)
        {
            
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "所有文件";
            //openFileDialog.Filter = "*";
            openFileDialog.FileName = string.Empty;
            openFileDialog.FilterIndex = 1;
            openFileDialog.Multiselect = false;
            openFileDialog.RestoreDirectory = true;
            //openFileDialog.DefaultExt = "exe";
            if (openFileDialog.ShowDialog() == false)
            {
                return;
            }
            else
            {
                // 读取选中的文件内容
                byte[] fileContent = File.ReadAllBytes(openFileDialog.FileName); 
                // 将文件内容转换为ByteArrayContent类型
                ByteArrayContent fileContentBytes = new ByteArrayContent(fileContent);

                // 创建HttpClient对象
                HttpClient client = new HttpClient();

                // 创建MultipartFormDataContent对象
                MultipartFormDataContent formData = new MultipartFormDataContent();
                formData.Add(new StringContent(FolderId), "FolderId");
                // 添加文件数据到MultipartFormDataContent对象中
                formData.Add(fileContentBytes, "file", openFileDialog.FileName); 
                // 设置上传地址
                string uploadUrl = "http://localhost:5610/baseadmin/netdiskfolderinfo/uploadfile";
                  
                // 发送POST请求
                HttpResponseMessage response = await client.PostAsync(uploadUrl, formData);
                if (response.StatusCode==HttpStatusCode.OK)
                {
                    var getFileList = _eventAggregator.GetEvent<PubSubEvent>();
                    getFileList.Publish();
                }
            }
            string txtFile = openFileDialog.FileName;
        }
        private async void Execute(string obj)
        {
            switch (obj)
            {
                case "Add":
                    CurrentInfo = new();
                    IsRightDrawerOpen = true;
                    break;
                case "Save":
                    var isSave = await _netdiskFolderService.SaveAsync(CurrentInfo);
                    if (isSave.Code == 0)
                    {
                        IsRightDrawerOpen = false;
                        _eventAggregator.SendMessage("保存成功!");
                        //InitFolders();
                        var myEvent = _eventAggregator.GetEvent<PubSubEvent>();
                        myEvent.Publish();
                    }
                    else
                    {

                    }

                    break;
                default:
                    break;
            }
        }
        private void Navigate(MenuBar obj)
        {
            if (obj == null || string.IsNullOrWhiteSpace(obj.NameSpace))
            {
                return;
            }
            if (obj.NameSpace== "IndexView")
            {
                IsTopVisibility = Visibility.Visible;
                Height = "50";
            }
            else
            {
                Height ="auto";
                IsTopVisibility = Visibility.Collapsed;
            }
            var regions = _regionManager.Regions[PrismManager.MainViewRegionName];
            regions.RequestNavigate(obj.NameSpace, back =>
            {
                journal = back.Context.NavigationService.Journal;

            });
        }
        
        void CreateMenuBar()
        {
            //Todo 替换为接口获取
            MenuBars.Add(new MenuBar() { Icon = "/Img/Main/IndexIcon.png", Title = "首页", NameSpace = "IndexView" }); 
            MenuBars.Add(new MenuBar() { Icon = "/Img/Main/TransfersIcon.png", Title = "传输", NameSpace = "TransfersView" });
            MenuBars.Add(new MenuBar() { Icon = "/Img/Main/IndexIcon.png", Title = "同步", NameSpace = "IndexView" });
            MenuBars.Add(new MenuBar() { Icon = "/Img/Main/messageIcon.png", Title = "消息", NameSpace = "MessageIconView" });
        }
    }
}
